package leetcode_1_200;

public class LeeCode_98 {
    public static void main(String[] args) {
        System.out.println(isValidBST(new TreeNode(2, new TreeNode(1), new TreeNode(3))));
        System.out.println(isValidBST(new TreeNode(5, new TreeNode(4),
                new TreeNode(6, new TreeNode(3), new TreeNode(7)))));
    }

    private static boolean isValidBST(TreeNode root) {
       return helper(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }
    private static boolean helper(TreeNode node, long min, long max){
        boolean l = true, r = true;
        if (node.left != null){
//            System.out.println("" + node.left.val + " " + min + " " + node.val);
            l = node.val > node.left.val && node.left.val > min && helper(node.left, min, node.val);
        }
        if (node.right != null){
//            System.out.println("" + node.right.val + " " + node.val + " " + max);
            r = node.val < node.right.val && node.right.val < max && helper(node.right, node.val, max) ;
        }
        return l && r;
    }

    private static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
